<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 输入框区域 -->
      <el-input placeholder="请输入内容" v-model="userInfo" clearable @clear="reloadInfo">
        <el-button slot="append" icon="el-icon-search" @click="searchInfo"></el-button>
      </el-input>
      <!-- 添加用户按钮 -->
      <el-button type="primary" @click="addUser">添加用户</el-button>

      <!-- 表格区域 -->
      <el-table :data="userlist" style="width: 100%" stripe border>
        <el-table-column type="index" label="#" width="40"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"> </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="state(scope.row)"
            >
            </el-switch>
            <!-- switch上的状态是双向数据绑定, 绑定到了mg_state上,所以只需要传递一个参数就可以 -->
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modify(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="dele(scope.row)"></el-button>
            <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="assign(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 3, 20]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户面板 -->
    <el-dialog v-dialogDrag title="添加用户" :visible.sync="addUsersVisible" width="50%" @close="addFormClosed">
      <el-form :model="addForm" :rules="addRules" ref="addRuleRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUsersVisible = false">取 消</el-button>
        <el-button type="primary" @click="confimAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息面板 -->
    <el-dialog v-dialogDrag title="修改用户信息" :visible.sync="modiUsersVisible" width="50%" @close="editFormClosed">
      <el-form :model="editForm" :rules="editRules" ref="editRuleRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modiUsersVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色面板 -->
    <el-dialog
      class="assign"
      v-dialogDrag
      title="分配角色"
      :visible.sync="assignVisible"
      width="50%"
      @close="assignFormClosed"
    >
      <p>
        当前用户:<span>{{ userInfoList.username }}</span>
      </p>

      <p>
        当前角色: <span>{{ userInfoList.role_name }}</span>
      </p>

      <p>
        分配新角色:
        <el-select v-model="selectID" slot="prepend" placeholder="请选择">
          <el-option
            :label="item.roleName"
            :value="item.id"
            v-for="(item, index) in userRoleList"
            :key="index"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmassign">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInfo: '',
      userlist: [],
      stateValue: '',
      total: 0,
      addUsersVisible: false,
      modiUsersVisible: false,
      assignVisible: false,
      selectID: '',
      userInfoList: {},
      userRoleList: [],
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 1,
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {
        uaername: '',
        email: '',
        mobile: '',
        id: '',
        role: '',
      },
      editRules: {
        email: [{ required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' },
        ],
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' },
        ],
        email: [{ required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    //读取用户列表信息
    this.getuserlist()
  },
  methods: {
    //当当前页数页数发生改变的时候, 就重新请求数据
    handleSizeChange(pagesize) {
      //把当前被点击的页数的值给查询对象
      this.queryinfo.pagesize = pagesize
      this.getuserlist()
    },

    //当每页显示的条数的数据发生改变后,
    handleCurrentChange(pagenum) {
      this.queryinfo.pagenum = pagenum
      this.getuserlist()
    },

    //获取用户列表数据
    async getuserlist() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryinfo,
      })

      //如果查询失败就返回错误信息
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },

    //点击添加用户按钮
    addUser() {
      //显示添加用户面板
      this.addUsersVisible = true
    },

    //确定添加
    confimAdd() {
      //进行表单预验证,如果验证没通过,就不发送请求
      this.$refs.addRuleRef.validate(async (val) => {
        if (!val) return this.$message.error('请输入合法信息')
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('创建用户信息失败')
        this.$message.success('创建用户信息成功')
        this.addUsersVisible = false
        this.getuserlist()
      })
    },

    //当添加用户面板被关闭的时候, 就重置表单
    addFormClosed() {
      // console.log(11)
      this.$refs.addRuleRef.resetFields()
    },

    //通过搜索按钮搜索指定用户信息
    searchInfo() {
      console.log(11)
      this.queryinfo.query = this.userInfo.trim()
      this.getuserlist()
      //   this.userInfo = ''
    },
    reloadInfo() {
      this.queryinfo.query = ''
      this.getuserlist()
    },

    //修改用户状态
    async state(role) {
      const { data: res } = await this.$http.put(`users/${role.id}/state/${role.mg_state}`)
      if (res.meta.status !== 200) {
        role.mg_state = !role.mg_state
        return this.$message.error('获取列表失败')
      }
    },

    //点击修改用户信息的按钮
    modify(role) {
      this.modiUsersVisible = true
      this.editForm.username = role.username
      this.editForm.id = role.id
      this.editForm.role = role.role_name
      this.editForm.email = role.email
      this.editForm.mobile = role.mobile
    },

    //进入修改用户信息面板后点击确认按钮确认修改用户信息
    confirmEdit() {
      // console.log(11);
      this.$refs.editRuleRef.validate(async (val) => {
        if (!val) return this.$message.error('请输入合法信息')
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.modiUsersVisible = false
        this.getuserlist()
      })
    },

    //修改用户信息的面板被关闭
    editFormClosed() {
      this.$refs.editRuleRef.resetFields()
    },

    //删除角色
    dele(role) {
      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {


        type: 'warning',
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${role.id}`)
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户信息成功')
        this.getuserlist()
        console.log(this.queryinfo)
      })
    },

    //给用户分配不同的角色信息
    async assign(role) {
      this.assignVisible = true
      // console.log(role.role_name)
      this.userInfoList.username = role.username
      this.userInfoList.role_name = role.role_name
      this.userInfoList.id = role.id
      if(!this.selectID) return this.$message.error('请选择角色')
      const { data: res } = await this.$http.get(`roles`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userRoleList = res.data
    },

    //关闭分配角色面板
    assignFormClosed(role) {
      this.assignVisible = false
      this.selectID = ''
    },

    //点击确定按钮确定分配角色
    async confirmassign() {
      const {data: res } = await this.$http.put(`users/${this.userInfoList.id}/role`, {
        rid: this.selectID
      })
      if (res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.assignVisible = false
      console.log(this.selectID);
      this.getuserlist()
      console.log(res);
    }
  },
}
</script>

<style scoped lang="less">
.el-card {
  margin-top: 20px;
}
.el-input {
  width: 300px;
  margin-right: 10px;
}
.el-table {
  margin-top: 10px;
}
.el-row {
  margin-bottom: 10px;
}
// .assign{
//   height: 400px;
// }
</style>
